package com.test.rabbitmq.workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-05-23 21:51
 */
public class Worker {
    private final static String TASK_QUEUE_NAME = "hello";
    private final static Logger LOGGER = LoggerFactory.getLogger(Worker.class);

    /**
     * Two things are required to make sure that messages aren't lost:
     * we need to mark both the queue and messages as durable
     */
    private static final boolean DURABLE = true;

    public static void main(String[] argv) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, DURABLE, false, false, null);
        LOGGER.info(" [*] Waiting for messages. To exit press CTRL+C");

        /**
         * This tells RabbitMQ not to give more than one message to a worker at a time.
         * Or, in other words, don't dispatch a new message to a worker until it has
         * processed and acknowledged the previous one. Instead,
         * it will dispatch it to the next worker that is not still busy.
         */
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");

            LOGGER.info(" [x] Received '" + message + "'");
            try {
                doWork(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LOGGER.info(" [x] Done");
                // send message acknowledgment manually
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        // acknowledgment is covered below
        boolean autoAck = false;
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {
        });
    }

    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.') {
                LOGGER.info("sleep 1 second");
                Thread.sleep(1000);
            }
        }
    }
}
